package jnpf.zc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.ActionResult;
import jnpf.exception.DataException;
import jnpf.model.visiual.superQuery.ConditionJsonModel;
import jnpf.model.visiual.superQuery.SuperQueryConditionModel;
import jnpf.model.visiual.superQuery.SuperQueryJsonModel;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.permission.service.AuthorizeService;
import jnpf.util.*;
import jnpf.zc.entity.ZcglZcczEntity;
import jnpf.zc.entity.ZcglZcczProcessEntity;
import jnpf.zc.entity.ZcglZcdjInfoEntity;
import jnpf.zc.mapper.ZcglZcczMapper;
import jnpf.zc.mapper.ZcglZcczProcessMapper;
import jnpf.zc.mapper.ZcglZcdjInfoMapper;
import jnpf.zc.model.zcglzccz.ZcglZcczForm;
import jnpf.zc.model.zcglzccz.ZcglZcczPagination;
import jnpf.zc.service.ZcglZcczService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * 资产处置
 * 版本： V3.2.0
 * 版权： 智果云科技（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2024-12-19
 */
@Service
public class ZcglZcczServiceImpl extends ServiceImpl<ZcglZcczMapper, ZcglZcczEntity> implements ZcglZcczService {


        @Autowired
        private GeneraterSwapUtil generaterSwapUtil;

        @Autowired
        private UserProvider userProvider;

        @Autowired
        private AuthorizeService authorizeService;

        @Autowired
        private ZcglZcczProcessMapper zcglZcczProcessMapper;
        @Autowired
        private ZcglZcczMapper zcglZcczMapper;
        @Autowired
        private ZcglZcdjInfoMapper zcglZcdjInfoMapper;


    @Override
    public List<ZcglZcczEntity> getList(ZcglZcczPagination zcglZcczPagination){
        return getTypeList(zcglZcczPagination,zcglZcczPagination.getDataType());
    }
    @Override
    public List<ZcglZcczEntity> getTypeList(ZcglZcczPagination zcglZcczPagination,String dataType){
        String userId=userProvider.get().getUserId();
        List<String> AllIdList =new ArrayList();
		List<List<String>> intersectionList =new ArrayList<>();
		int total=0;
		int zcglZcczNum =0;
        QueryWrapper<ZcglZcczEntity> zcglZcczQueryWrapper=new QueryWrapper<>();
		List<String> allSuperIDlist = new ArrayList<>();
		String superOp ="";
	if (ObjectUtil.isNotEmpty(zcglZcczPagination.getSuperQueryJson())){
		SuperQueryJsonModel superQueryJsonModel = JsonUtil.getJsonToBean(zcglZcczPagination.getSuperQueryJson(), SuperQueryJsonModel.class);
		String matchLogic = superQueryJsonModel.getMatchLogic();
		List<ConditionJsonModel> superQueryList = JsonUtil.getJsonToList(superQueryJsonModel.getConditionJson(), ConditionJsonModel.class);
		for (ConditionJsonModel conditionjson : superQueryList){
            Map<String, Object> map = JsonUtil.stringToMap(conditionjson.getAttr());
            Map<String, Object> configMap = JsonUtil.stringToMap(map.get("__config__").toString());
            String tableName = configMap.get("relationTable")!=null ? String.valueOf(configMap.get("relationTable")) : String.valueOf(configMap.get("tableName"));
		    if (map.get("multiple") != null) {
		        if (Boolean.valueOf(String.valueOf(map.get("multiple"))) && ObjectUtil.isNull(conditionjson.getFieldValue())) {
		            conditionjson.setFieldValue("[]");
		        }
		    }
            conditionjson.setTableName(tableName);
		}
		List<String> allSuperList = new ArrayList<>();
		List<List<String>> intersectionSuperList  = new ArrayList<>();
        int zcglZcczNum1 = 0;
        QueryWrapper<ZcglZcczEntity> zcglZcczSuperWrapper = new QueryWrapper<>();
        zcglZcczNum1 = generaterSwapUtil.getCondition(new SuperQueryConditionModel(zcglZcczSuperWrapper,superQueryList,matchLogic,"zcglZccz")
        ,new ZcglZcczEntity(),zcglZcczNum1);
            if (zcglZcczNum1>0){
            List<String> zcglZcczList =this.list(zcglZcczSuperWrapper).stream().map(ZcglZcczEntity::getId).collect(Collectors.toList());
            allSuperList.addAll(zcglZcczList);
            intersectionSuperList.add(zcglZcczList);
            }
		superOp = matchLogic;
		//and or
		if(matchLogic.equalsIgnoreCase("and")){
		    allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
		}else{
		    allSuperIDlist = allSuperList;
		}
    }
    boolean pcPermission = false;
    boolean appPermission = false;
    boolean	isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
    if(isPc && pcPermission){
		if (!userProvider.get().getIsAdministrator()){
				Object zcglZcczObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglZcczQueryWrapper,zcglZcczPagination.getMenuId(),"zcgl_zccz"));
            if (ObjectUtil.isEmpty(zcglZcczObj)){
                return new ArrayList<>();
            } else {
                zcglZcczQueryWrapper = (QueryWrapper<ZcglZcczEntity>)zcglZcczObj;
                zcglZcczNum++;
            }
        }
    }
    if(!isPc && appPermission){
		if (!userProvider.get().getIsAdministrator()){
			Object zcglZcczObj=authorizeService.getCondition(new AuthorizeConditionModel(zcglZcczQueryWrapper,zcglZcczPagination.getMenuId(),"zcglZccz"));
            if (ObjectUtil.isEmpty(zcglZcczObj)){
                return new ArrayList<>();
            } else {
            zcglZcczQueryWrapper = (QueryWrapper<ZcglZcczEntity>)zcglZcczObj;
            zcglZcczNum++;
			}
		}
    }
        if(isPc){
			if(ObjectUtil.isNotEmpty(zcglZcczPagination.getDisposalMethod())){
            zcglZcczNum++;
                zcglZcczQueryWrapper.lambda().eq(ZcglZcczEntity::getDisposalMethod,zcglZcczPagination.getDisposalMethod());
                    }
			if(ObjectUtil.isNotEmpty(zcglZcczPagination.getDisposalInstructions())){
            zcglZcczNum++;
            zcglZcczQueryWrapper.lambda().like(ZcglZcczEntity::getDisposalInstructions,zcglZcczPagination.getDisposalInstructions());
                    }
        }
		List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
		if (total>0){
		if (intersection.size()==0){
		    intersection.add("jnpfNullList");
		}
         zcglZcczQueryWrapper.lambda().in(ZcglZcczEntity::getId, intersection);
		}
        //是否有高级查询
		if (StringUtil.isNotEmpty(superOp)){
		    if (allSuperIDlist.size()==0){
		        allSuperIDlist.add("jnpfNullList");
		    }
		List<String> finalAllSuperIDlist = allSuperIDlist;
            zcglZcczQueryWrapper.lambda().and(t->t.in(ZcglZcczEntity::getId, finalAllSuperIDlist));
		}

        //排序
        if(StringUtil.isEmpty(zcglZcczPagination.getSidx())){
        zcglZcczQueryWrapper.lambda().orderByDesc(ZcglZcczEntity::getId);
        }else{
            try {
            	String sidx = zcglZcczPagination.getSidx();
                ZcglZcczEntity zcglZcczEntity = new ZcglZcczEntity();
				Field declaredField = zcglZcczEntity.getClass().getDeclaredField(sidx);
				declaredField.setAccessible(true);
				String value = declaredField.getAnnotation(TableField.class).value();
                 zcglZcczQueryWrapper="asc".equals(zcglZcczPagination.getSort().toLowerCase())?zcglZcczQueryWrapper.orderByAsc(value):zcglZcczQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if("0".equals(dataType)){
            if((total>0 && AllIdList.size()>0) || total==0){
                Page<ZcglZcczEntity> page=new Page<>(zcglZcczPagination.getCurrentPage(), zcglZcczPagination.getPageSize());
                IPage<ZcglZcczEntity> userIPage=this.page(page, zcglZcczQueryWrapper);
                return zcglZcczPagination.setData(userIPage.getRecords(),userIPage.getTotal());
            }else{
                List<ZcglZcczEntity> list = new ArrayList();
                return zcglZcczPagination.setData(list, list.size());
            }
        }else{
            return this.list(zcglZcczQueryWrapper);
        }
    }


    @Override
    public ZcglZcczEntity getInfo(String id){
        QueryWrapper<ZcglZcczEntity> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(ZcglZcczEntity::getId,id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZcglZcczEntity entity){
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZcglZcczEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ZcglZcczEntity entity){
        if(entity!=null){
            this.removeById(entity.getId());
        }
    }
    //子表方法

    //列表子表数据方法



    //验证表单唯一字段
    @Override
    public boolean checkForm(ZcglZcczForm form, int i) {
        int total = 0;
		boolean isUp =StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
		String id="";
		if (isUp){
			 id = form.getId();
		}
        if (total>0){
        return true;
        }
        return false ;
    }

    @Override
    public ActionResult addZccz(ZcglZcczForm zcglZcczForm) throws DataException {
        ZcglZcczProcessEntity zcglZcczProcessEntity = zcglZcczForm.getZcglZcczProcessEntity();
        if(ObjectUtil.isEmpty(zcglZcczProcessEntity)){
            throw new DataException("资产数据不能为空");
        }
        zcglZcczProcessEntity.setParentid(zcglZcczForm.getId());
        zcglZcczProcessEntity.setCreatortime(new Date());
        zcglZcczProcessEntity.setState(ZcglZcczProcessEntity.STATE_1);
        zcglZcczProcessMapper.insert(zcglZcczProcessEntity);
        return ActionResult.success("新增成功");
    }

    @Override
    public ActionResult queryZcczgc(String id) throws DataException {
        ZcglZcczEntity zcglZcczEntity = zcglZcczMapper.selectById(id);
        ZcglZcczForm zcglZcczForm = new ZcglZcczForm();
        BeanUtil.copyProperties(zcglZcczEntity,zcglZcczForm);
        String disposalAssets = zcglZcczEntity.getDisposalAssets();
        if(ObjectUtil.isEmpty(disposalAssets)){
            throw new DataException("还未创建资产处置信息，请先创建");
        }
        List<String> listAssets = Arrays.stream(disposalAssets.split(","))
                .collect(Collectors.toList());

        List<ZcglZcdjInfoEntity> zcglZcdjInfoEntities = zcglZcdjInfoMapper.selectBatchIds(listAssets);
        zcglZcczForm.setZcglZcdjInfoEntities(zcglZcdjInfoEntities);

        List<ZcglZcczProcessEntity> listProcesss = zcglZcczProcessMapper.selectList(new QueryWrapper<ZcglZcczProcessEntity>()
                .eq("F_PARENTID", id)
        );
        //根据处置完成时间倒序排序
        listProcesss = listProcesss.stream()
                .sorted(Comparator.comparing(ZcglZcczProcessEntity::getCreatortime).reversed())
                .collect(Collectors.toList());
        zcglZcczForm.setZcglZcczProcessEntitys(listProcesss);
        return ActionResult.success(zcglZcczForm);
    }

    @Override
    public ActionResult completeZccz(ZcglZcczForm zcglZcczForm) throws DataException {
        ZcglZcczProcessEntity zcglZcczProcessEntity = zcglZcczForm.getZcglZcczProcessEntity();
        if(ObjectUtil.isEmpty(zcglZcczProcessEntity)){
            throw new DataException("资产数据不能为空");
        }
        zcglZcczProcessEntity.setParentid(zcglZcczForm.getId());
        zcglZcczProcessEntity.setState(ZcglZcczProcessEntity.STATE_2);
        zcglZcczProcessMapper.insert(zcglZcczProcessEntity);

        ZcglZcczEntity zcglZcczEntity = new ZcglZcczEntity();
        BeanUtil.copyProperties(zcglZcczForm,zcglZcczEntity);
        zcglZcczEntity.setDisposalState(ZcglZcczEntity.DISPOSAL_STATE_2);
        zcglZcczEntity.setEndTime(zcglZcczProcessEntity.getCreatortime());
        zcglZcczEntity.setUpdateTime(zcglZcczProcessEntity.getCreatortime());
        this.updateById(zcglZcczEntity);
        return ActionResult.success("新增成功");
    }

    @Override
    public ActionResult completeZc(ZcglZcczForm zcglZcczForm) {
        ZcglZcczEntity zcglZcczEntity = new ZcglZcczEntity();
        BeanUtil.copyProperties(zcglZcczForm,zcglZcczEntity);
        zcglZcczEntity.setDisposalState(ZcglZcczEntity.DISPOSAL_STATE_2);
        baseMapper.updateById(zcglZcczEntity);
        return ActionResult.success("操作成功");
    }


}
